package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
@Slf4j
@Transactional
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    /**
     * 用户登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {


        //1.正常登录
        if(StringUtils.isNotBlank(dto.getPhone()) && StringUtils.isNotBlank(dto.getPassword())){
            //1.1 根据手机号查询用户

            ApUser dbUser = this.getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone,dto.getPhone()));
            if(null == dbUser ){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"用户不存在");
            }

            //1.2 比对密码
            String salt = dbUser.getSalt();
            String pswd = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
            if(!pswd.equals(dbUser.getPassword())){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }

            //1.3 比对成功  生成token返回

            String token = AppJwtUtil.getToken(dbUser.getId().longValue());
            Map<String,Object> map = new HashMap<>();
            map.put("token",token);
            dbUser.setPassword("");
            dbUser.setSalt("");
            map.put("user",dbUser);

            return ResponseResult.okResult(map);

        }else {
            //2.游客登录
            String token = AppJwtUtil.getToken(0L);
            Map<String,Object> map = new HashMap<>();
            map.put("token",token);

            return ResponseResult.okResult(map);
        }
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 用户注册
     * @param apUser
     * @return
     */
    @Override
    public ResponseResult register(ApUser apUser) {

        // 1. 参数校验失败，抛出异常
        if (StringUtils.isBlank(apUser.getPhone()) || StringUtils.isBlank(apUser.getPassword())) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 注册的用户已存在，抛出异常
        ApUser registerUser = this.getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, apUser.getPhone()));
        if (registerUser != null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 3. 注册的用户不存在，存入数据库，注册成功
        String salt = UUID.randomUUID().toString().replaceAll("-", "");
        String password = apUser.getPassword();
        // 密码和盐的字节数组一起 md5 加密
        password = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        apUser.setSalt(salt);
        apUser.setPassword(password);
        apUser.setCreatedTime(new Date());
        this.save(apUser);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
